package es.decloud.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import es.decloud.dao.CentroDao;
import es.decloud.model.Centro;
import es.decloud.model.Usuario;

/**
 * This class interacts with hibernate session to save/delete and retrieve
 * Centro objects.
 */
@Repository("centroDao")
public class CentroDaoHibernate extends GenericDaoHibernate<Centro, Long> implements CentroDao {

	/**
	 * Constructor to create a Generics-based version using Role as the entity
	 */
	public CentroDaoHibernate() {
		super(Centro.class);
	}

	/**
	 * {@inheritDoc}
	 */
	public Centro getCentroByNombre(String nombre) {
		List centros = getSession().createCriteria(Centro.class).add(Restrictions.eq("nombre", nombre)).list();
		if (centros.isEmpty()) {
			return null;
		}
		else {
			return (Centro) centros.get(0);
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	public Centro saveCentro(Centro centro) {
		if (log.isDebugEnabled()) {
			log.debug("user's id: " + centro.getId());
		}
		getSession().saveOrUpdate(centro);
		// necessary to throw a DataIntegrityViolation and catch it in
		// UserManager
		getSession().flush();
		return centro;
	}

	/**
	 * Overridden simply to call the saveUser method. This is happening because
	 * saveUser flushes the session and saveObject of BaseDaoHibernate does not.
	 * 
	 * @param user
	 *            the user to save
	 * @return the modified user (with a primary key set if they're new)
	 */
	@Override
	public Centro save(Centro centro) {
		return this.saveCentro(centro);
	}
}
